import React, { Component } from 'react';
import 'antd/dist/antd.css';
import store from "./store";
import { getChangeInputValueAction, getAddTodoItemAction, getDeleteTodoItemAction, getTodoList} from './store/actionCreators';
import TodoListUI from "./TodoListUI";

class TodoList02 extends Component {

    constructor(props){
        super(props);
        this.state = store.getState();

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleStoreChange = this.handleStoreChange.bind(this);
        this.handleBtnClick = this.handleBtnClick.bind(this);

        this.handleDeleteItem = this.handleDeleteItem.bind(this);

        // listen the update of store (store's state comes from reducer)
        store.subscribe(this.handleStoreChange);

    }

    handleBtnClick () {
        // the click handling method does not contain data
        const action = getAddTodoItemAction();
        store.dispatch (action);
    }

    /**
     * update the new state to the react component
     */
    handleStoreChange () {
        this.setState(store.getState());
    }

    /**
     * create input change action and dispatch to the reducer
     * @param e
     */
    handleInputChange (e) {
        // action is merely an object which is used to deliver the operation msg
        const action = getChangeInputValueAction(e.target.value);

        // use store's method 'dispatch' to deliver the action to the store obj
        // store obj will deliver the prevState and action to the reducer
        store.dispatch (action);
    }

    handleDeleteItem (index) {
        const action = getDeleteTodoItemAction(index);
        store.dispatch (action);
    }

    /**
     * business and logic of ajax request could be complex
     * so it is better to write in the action
     */
    componentDidMount () {
        const action = getTodoList();
        // the function 'action' will be executed once was dispatched
        store.dispatch (action);
    }

    render () {
        return (
            <TodoListUI
                inputValue={this.state.inputValue}
                list={this.state.list}
                handleInputChange={this.handleInputChange}
                handleBtnClick={this.handleBtnClick}
                handleDeleteItem={this.handleDeleteItem}

            />
        )
    }

}

export default TodoList02;